import React, { useCallback, useEffect, useMemo, useState } from 'react';

import { Button, Card, Form, Input, message, Spin, Tooltip, TreeSelect } from 'antd';
import { history } from 'umi'

import { BottomAction } from '@/components';
import OrganizationSelect from '@/components/OrganizationSelect';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { useRequest } from '@/hooks';
import { DynamicTable } from '@/pages/TurnoverSetting/EntrySetting/components';
import { onSuccessBySave } from '@/pages/TurnoverSetting/EntrySetting/util';
import pageTabUtil from '@/utils/pageTabUtil';
import { array2Tree } from '@/utils/tree';

import {
    getDutyListByOrganizationV2,
    getEntryFlowConfig,
    getEntryFlowDefaultConfig,
    saveEntryFlowConfig
} from '../services';
import styles from './index.less';

const { TreeNode } = TreeSelect;

// 格式化结果, 因为这个页面的行政机构只能有一个值, 但是服务端的返回的是一个数组, 要预处理.
const formatResult = res => {
    if (res) {
        const { code, msg } = res;
        if (code === 10000) {
            const result = res.data;
            result.administrativeScope = result.administrativeScope?.length ? result.administrativeScope[0] : '';
            return result;
        }
        // 配置已变更, 当前访问的数据是旧数据, 要返回列表并刷新列表
        if (code === 21008) {
            message.warning(msg);
            history.push({
                pathname: '/office/personnelManagement/onboardAndLeave/setting/index',
                state: { tabRoute: true, tabRefresh: true, closeTab: true }
            });
            return undefined;
        }
        message.error(msg);
    }
    return undefined;
};

// 处理人所在的岗位必须是在该行政机构下面的. 通过自定义的方式来优化禁用的样式
const generateTreeNodes = treeData =>
    treeData.map(item => (
        <TreeNode
            value={item.value}
            key={item.key}
            title={item.title}
            selectable={item.selectable}
            className={!item.selectable ? 'disabled' : null}
        >
            {item.children?.length && generateTreeNodes(item.children)}
        </TreeNode>
    ));

/**
 * 入职流程配置详情
 */
const EntryFlowSettingEdit = ({ form, location }) => {
    const { query } = location;
    const { id } = query;
    const action = useMemo(() => (id ? 'edit' : 'create'), [id]);
    const currentUser = JSON.parse(localStorage.getItem('user') || {});
    const { administrativeOrganizationCode } = currentUser || {};

    // 编辑时获取记录
    const { data, loading } = useRequest(() => getEntryFlowConfig(id), {
        ready: action === 'edit' && id,
        formatResult
    });

    // 创建数据时, 获取默认配置
    const { data: defaultData, loading: defaultDataLoading } = useRequest(getEntryFlowDefaultConfig, {
        ready: action === 'create',
        formatResult
    });

    // 获取处理人的数据
    const administrativeScope =
        form.getFieldValue('administrativeScope') ||
        (data?.isDefault === 1 && data.administrativeScope) ||
        administrativeOrganizationCode;
    const { data: dealDutyData, loading: dealDutyLoading } = useRequest(
        () => getDutyListByOrganizationV2({ organizationCode: administrativeScope, showTreeFlag: 0 }),
        {
            ready: !!administrativeScope,
            refreshDeps: [administrativeScope],
            formatResult: res => {
                // 数据转换
                const filterDuties = tree =>
                    tree.map(i => ({
                        title: i.dutyAlias,
                        value: i.dutyCode,
                        key: i.dutyCode,
                        selectable: i.disable === 0
                    }));
                const filterEnableChildren = item => {
                    let result = false;
                    if (item.children.length) {
                        for (let i = 0; i < item.children.length; i += 1) {
                            if (filterEnableChildren(item.children[i])) {
                                result = true;
                            }
                        }
                    } else {
                        result = item.duties.some(duty => duty.disable === 0);
                    }
                    return result;
                };

                const filterTree = tree =>
                    tree
                        .map(({ children, organizationName, organizationCode, duties, ...props }) => {
                            if (
                                children?.filter(filterEnableChildren).length > 0 ||
                                duties?.filter(item => item.disable === 0).length > 0
                            ) {
                                return {
                                    children: [...filterTree(children), ...filterDuties(duties)],
                                    title: organizationName,
                                    value: organizationCode,
                                    key: organizationCode,
                                    selectable: false,
                                    ...props
                                };
                            }
                            return false;
                        })
                        .filter(Boolean);

                if (res) {
                    const { code, msg } = res;
                    if (code === 10000) {
                        const newData = array2Tree(
                            res.data
                                // .filter(item => item?.duties?.some(duty => duty.disable === 0))
                                .map(item => ({ ...item, duties: item.duties.filter(duty => duty.disable === 0) })),
                            'organizationPath',
                            'parentOrganizationPath'
                        );
                        return filterTree(newData);
                    }
                    message.error(msg);
                }
                return undefined;
            }
        }
    );

    // 提交
    const { run: submitRun, loading: submitLoading } = useRequest(submitData => saveEntryFlowConfig(submitData), {
        manual: true,
        onSuccess: onSuccessBySave
    });

    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                const submitData = {
                    ...data,
                    isDefault: data?.isDefault ?? 0,
                    ...values,
                    content: values.content?.filter(Boolean)
                };
                // 提交数据预处理
                submitData.administrativeScope = [submitData.administrativeScope];
                submitRun(submitData);
            }
        });
    };

    // 配置内容列配置
    const columns = useMemo(
        () => [
            {
                dataIndex: 'editFlag',
                hide: true
            },
            {
                dataIndex: 'assignName',
                hide: true
            },
            {
                dataIndex: 'assignType',
                hide: true
            },
            {
                title: '流程顺序',
                dataIndex: 'processSort',
                width: '120px'
            },
            {
                title: '流程名称',
                dataIndex: 'processDescription'
            },
            {
                title: '处理人',
                dataIndex: 'assignCode',
                width: '250px',
                render: ({ text, record, fieldDecorator }) => (
                    <>
                        {!record.editFlag && <Tooltip title="默认处理人, 不可修改">{record.assignName}</Tooltip>}
                        {record.editFlag &&
                            fieldDecorator('assignCode', {
                                initialValue: text || undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '不能为空'
                                    }
                                ]
                            })(
                                <TreeSelect
                                    showArrow
                                    allowClear
                                    showSearch
                                    placeholder="请选择"
                                    dropdownStyle={{ maxHeight: 250, maxWidth: 400, overflow: 'auto' }}
                                    treeDefaultExpandAll
                                    treeNodeFilterProp="title"
                                    dropdownClassName={styles.treeItemHasDisabledStyle}
                                    style={{ width: 304 }}
                                >
                                    {generateTreeNodes(dealDutyData || [])}
                                </TreeSelect>
                            )}
                    </>
                )
            }
        ],
        [dealDutyData]
    );

    // 配置内容的初始值
    const [contentInitialValue, setContentInitialValue] = useState([]);

    // 初始化动态表格的值
    useEffect(() => {
        if (action === 'create' && defaultData) {
            setContentInitialValue(defaultData?.content || []);
        }
    }, [action, defaultData]);
    useEffect(() => {
        if (action === 'edit' && data) {
            setContentInitialValue(data?.content || []);
        }
    }, [action, data]);

    // 行政机构值改变, 联动处理人数据
    const handleAdministrativeScopeChange = useCallback(
        value => {
            const contentData =
                form.getFieldValue('content')?.map(item => {
                    if (item.editFlag) {
                        return { ...item, assignCode: '' };
                    }
                    return item;
                }) ||
                defaultData?.content ||
                [];

            form.setFieldsValue({
                administrativeScope: value,
                // 联动, 清空配置内容的处理人下拉框的值
                content: contentData
            });
            // 因为 DynamicTable 的值是内部管理的, 要通过 initialValue 来重置值
            setContentInitialValue(contentData);
            // eslint-disable-next-line react-hooks/exhaustive-deps
        },
        [defaultData, form]
    );

    const hasAdministrativeScope =
        action === 'edit' ? data?.administrativeScope : form.getFieldValue('administrativeScope');

    return (
        <PageHeaderWrapper>
            <Card
                title={`${action === 'edit' ? '编辑' : '添加'}模板`}
                bordered={false}
                loading={loading || defaultDataLoading}
            >
                <Form className={styles.formWrap} style={{ marginBottom: 100 }}>
                    <Form.Item label="配置名称">
                        {form.getFieldDecorator('settingName', {
                            initialValue: data?.settingName || undefined,
                            rules: [
                                {
                                    required: true,
                                    message: '配置名称不能为空'
                                }
                            ]
                        })(<Input placeholder="请输入" allowClear maxLength={200} style={{ width: 528 }} />)}
                    </Form.Item>
                    <Form.Item label="适用行政机构">
                        {data?.isDefault === 1 && '全集团'}
                        {data?.isDefault === 1 &&
                            form.getFieldDecorator('administrativeScope', {
                                initialValue: data?.administrativeScope || undefined
                            })(<input type="hidden" />)}
                        {data?.isDefault !== 1 &&
                            form.getFieldDecorator('administrativeScope', {
                                initialValue: data?.administrativeScope || administrativeOrganizationCode || undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '适用行政机构不能为空'
                                    }
                                ]
                            })(
                                <OrganizationSelect
                                    style={{ width: 528 }}
                                    isNeedPermission={false}
                                    onlyCompany
                                    placeholder="请选择"
                                    onChange={handleAdministrativeScopeChange}
                                />
                            )}
                    </Form.Item>
                    {hasAdministrativeScope && (
                        <Form.Item label="配置内容">
                            <p style={{ color: 'rgba(0,0,0,0.30)' }}>
                                若流程处理人岗位当前无员工在职，系统将逐级向上寻找该岗位的上级处理相关流程
                            </p>
                            {dealDutyData ? false : dealDutyLoading && <Spin spinning />}
                            {!(dealDutyData ? false : dealDutyLoading) && (
                                <DynamicTable
                                    form={form}
                                    initialValue={contentInitialValue}
                                    fieldName="content"
                                    columns={columns}
                                    disabled
                                />
                            )}
                        </Form.Item>
                    )}
                    <BottomAction>
                        <Button onClick={() => pageTabUtil.goBack()}>取消</Button>
                        <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                            提交
                        </Button>
                    </BottomAction>
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

EntryFlowSettingEdit.displayName = 'EntryFlowSettingEdit';

export default React.memo(Form.create()(EntryFlowSettingEdit));
